<template>
  <div class="app-container">
    <!-- 调度日志详细 -->
    <vxe-modal
      v-model="open"
      :z-index="100"
      :esc-closable="true"
      transfer
      show-footer
      lock-view
      lock-scroll
      :position="{ top: 100, left: 'center' }"
      title="日志详细"
      destroy-on-close
      width="50%"
      height="60%"
      resize>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日志序号：">{{ form.jobLogId }}</el-form-item>
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
            <el-form-item label="执行时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用方法：">{{ form.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日志信息：">{{ form.jobMessage }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行状态：">
              <div v-if="form.status == 0">正常</div>
              <div v-else-if="form.status == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常信息：" v-if="form.status == 1">{{ form.exceptionInfo }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行参数：">
              <json-viewer :value="form.jobParams ? JSON.parse(form.jobParams) : null"
                           :expand-depth=5
                           copyable
                           boxed/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行结果：">
              <json-viewer :value="form.jobResult ? JSON.parse(form.jobResult) : null"
                           :expand-depth=5
                           boxed
                           copyable/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </vxe-modal>
    <div class="app-content-container">
      <grid-table ref="gridTable"
                  border="inner"
                  name="JobLog"
                  :loading.sync="loading"
                  :query="queryParams"
                  :buttons.sync="buttons"
                  :perfect="false"
                  :show-search="true"
                  :columns="tableColumns"
                  :table-data="jobLogList"
                  @cell-dblclick="({row}) => { handleView(row) }"
                  @remote-method="getList">
        <template v-slot:search-form>
          <el-form :model="queryParams" size="mini" ref="queryForm" :inline="true" v-show="showSearch" class="inline-form">
            <el-form-item label="任务ID" prop="jobId">
              <el-input
                v-model="queryParams.jobId"
                placeholder="请输入任务ID"
                clearable
                style="width: 240px"
                @change="handleJobIdChange"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="任务名称" prop="jobName">
              <el-input
                v-model="queryParams.jobName"
                placeholder="请输入任务名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="任务组名" prop="jobGroup">
              <el-select
                v-model="queryParams.jobGroup"
                placeholder="请任务组名"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in jobGroupOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="执行状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择执行状态"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="执行时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </template>
      </grid-table>
    </div>
  </div>
</template>

<script>
import { listJobLog, delJobLog, exportJobLog, cleanJobLog } from "@/api/monitor/jobLog";
import GridTable from '@/components/GridTable';
import JsonViewer from 'vue-json-viewer';

export default {
  name: "JobLog",
  components: { GridTable, JsonViewer },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 按钮数组
      buttons: [
        { type: 'add', disabled: true },
        { type: 'edit', disabled: true },
        { type: 'import', disabled: true },
        { type: 'delete', name: '清空', click: this.handleClean, permit: 'monitor:job:remove' },
        { type: 'search', click: this.handleQuery, permit: 'monitor:job:query'},
        { type: 'reset', click: this.resetQuery, permit: 'monitor:job:query'},
        { type: 'export', click: this.handleExport, permit: 'monitor:job:export'},
      ],
      tableColumns: [
        { title: '日志编号', width: 100, field: 'jobLogId', align: 'center', headerAlign: 'center' },
        { title: '任务ID', width: 100, field: 'jobId', align: 'center', headerAlign: 'center' },
        { title: '任务名称', width: 120, field: 'jobName', headerAlign: 'center', align: 'center' },
        { title: '任务组名', width: 120, field: 'jobGroup', headerAlign: 'center', align: 'center' },
        { title: '调用目标字符串', width: "auto", field: 'invokeTarget', headerAlign: 'center', align: 'center'},
        { title: '日志信息', width: "auto", field: 'jobMessage', headerAlign: 'center', align: 'center'},
        { title: '运行状态', width: 160, headerAlign: 'center', align: 'center', 
          slots: {
            default: ({ row }) => {
              const type = row.status === '0' ? 'success' : 'danger'
              return [<el-tag type={type} class="tag-item" size="mini" effect="dark" >{ this.statusFormat(row) }</el-tag>]
            }
          }
        },
        { title: '运行时间', width: 160, headerAlign: 'center', align: 'center', sortable: true,
          slots: {
            default: ({ row }) => {
              return [<span>{ row.createTime }</span>]
            }
          }
        },
        {
          title: '操作', width: 120, headerAlign: 'center', align: 'center',
          slots: {
            default: ({ row }) => {
              return [
                <el-button size="mini" type="text" icon="el-icon-view" nativeOnClick={() => this.handleView(row)}>
                  详细
                </el-button>
              ]
            }
          }
        }
      ],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 调度日志表格数据
      jobLogList: [],
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 分页参数，
      // 执行状态字典
      statusOptions: [],
      // 任务组名字典
      jobGroupOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        jobId: undefined,
        jobName: undefined,
        jobGroup: undefined,
        status: undefined
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_job_run_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_job_group").then(response => {
      this.jobGroupOptions = response.data;
    });
  },
  methods: {
    handleJobIdChange(val) {
      console.log(val, this.$route.query.jobId)
      if (!val && this.$route.query.jobId) {
        delete this.$route.query.jobId
      }
    },
    /** 查询调度日志列表 */
    getList(jobId) {
      const query = this.$route.query
      this.queryParams.jobId = query.jobId
      this.loading = true;
      listJobLog(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.jobLogList = response.rows;
          this.queryParams.total = response.total;
          this.loading = false;
        }
      );
    },
    // 执行状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 任务组名字典翻译
    jobGroupFormat(row, column) {
      return this.selectDictLabel(this.jobGroupOptions, row.jobGroup);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobLogId);
      this.multiple = !selection.length;
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jobLogIds = this.ids;
      this.$confirm('是否确认删除调度日志编号为"' + jobLogIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delJobLog(jobLogIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 清空按钮操作 */
    handleClean() {
      this.confirm("是否确认清空所有调度日志数据项?", "警告")
        .then(type => {
          if (type === 'confirm') {
            return cleanJobLog().then(() => {
              this.getList();
              this.msgSuccess("清空成功");
            })
          }
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.confirm("是否确认导出所有调度日志数据项?", "警告")
        .then(type => {
          if (type === 'confirm') {
            return exportJobLog(queryParams).then(response => {
              this.download(response.msg);
            })
          }
        }).catch(function() {});
    }
  }
};
</script>
